package Entwickler;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;


public class OBJLoader {
	public static Polygon Load(String str){
		StringBuilder contents = new StringBuilder();
	    try {
	      BufferedReader input =  new BufferedReader(new FileReader(str));
	      try {
	        String line = null;
	        while ((line = input.readLine()) != null){
	        	contents.append(line);
	        	contents.append("<:>");
	        }
	      }
	      finally {
	        input.close();
	      }
	    }
	    catch (Exception ex){
	      ex.printStackTrace();
	    }
	    
	    String loadedFile = contents.toString();
	    String[] splitedElements = loadedFile.split("<:>");
	    
	    Polygon polygon = new Polygon(0, 0, 0);
	    ArrayList<Point> points = new ArrayList<Point>();
	    
	    for(int i = 0; i < splitedElements.length; i++) {
	    	String[] tmpSplittedElements = splitedElements[i].split(" ");
	    	if(tmpSplittedElements[0].equals("v")) {
	    		polygon.points.add(new Point(Float.parseFloat(tmpSplittedElements[1]), Float.parseFloat(tmpSplittedElements[2]), Float.parseFloat(tmpSplittedElements[3]), polygon));
	    	}
	    }
	    for(int i = 0; i < splitedElements.length; i++) {
	    	String[] tmpSplittedElements = splitedElements[i].split(" ");
	    	for (int j = 0; j < tmpSplittedElements.length; j++) {
	    		tmpSplittedElements[j] = tmpSplittedElements[j].split("/")[0];
			}
	    	if(tmpSplittedElements[0].equals("f")) {
	    		int[] l1 = {polygon.points.get(Integer.parseInt(tmpSplittedElements[1])-1).identifier, polygon.points.get(Integer.parseInt(tmpSplittedElements[2])-1).identifier};
	    		polygon.lines.add(l1);
	    		int[] l2 = {polygon.points.get(Integer.parseInt(tmpSplittedElements[2])-1).identifier, polygon.points.get(Integer.parseInt(tmpSplittedElements[3])-1).identifier};
	    		polygon.lines.add(l2);
	    		if(tmpSplittedElements.length == 4){
	    			int[] l3 = {polygon.points.get(Integer.parseInt(tmpSplittedElements[3])-1).identifier, polygon.points.get(Integer.parseInt(tmpSplittedElements[1])-1).identifier};
		    		polygon.lines.add(l3);
	    		}else if(tmpSplittedElements.length == 5){
	    			int[] l3 = {polygon.points.get(Integer.parseInt(tmpSplittedElements[3])-1).identifier, polygon.points.get(Integer.parseInt(tmpSplittedElements[4])-1).identifier};
		    		polygon.lines.add(l3);
		    		int[] l4 = {polygon.points.get(Integer.parseInt(tmpSplittedElements[4])-1).identifier, polygon.points.get(Integer.parseInt(tmpSplittedElements[1])-1).identifier};
		    		polygon.lines.add(l4);
	    		}
	    	}
	    }
    	return polygon;	    
	}
}
